type 和 interface 的异同

相同点

1
2
3
4
5
6
7
interface IAnimal {
name: string;
}

type Animal = {
name: string,
};

泛型

1
2
3
4
5
6
7
interface IAnimal<p = string> {
name: p;
}

type Animal<p = string> = {
name: p,
};

交叉继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type Robot = {
power: number,
};

interface IRobot {
name: string;
}

interface IRobotAnimal1 extends IAnimal, IRobot {}
interface IRobotAnimal2 extends IAnimal, Robot {}
interface IRobotAnimal3 extends Animal, IRobot {}
interface IRobotAnimal4 extends Animal, Robot {}

type RobotAnimal1 = IAnimal & IRobot;
type RobotAnimal2 = IAnimal & Robot;
type RobotAnimal3 = Animal & IRobot;
type RobotAnimal4 = Animal & Robot;

实现

1
2
3
4
5
6
7
class Dog implements IAnimal {
name: string = 'doge';
}

class Cat implements Animal {
name: string = 'cat cat';
}

继承类

1
2
3
4
5
6
7
8
9
10
11
class Control {
private state: any;
}

interface ISelectableControl extends Control {
select(): void;
}

type SelectableControl = Control & {
select(): () => void;
};

函数

1
2
3
4
5
6
7
8
9
10
11
12
type Bark = (x: string) => void;

interface IBark {
(x: string): void;
}

// 函数 泛型
type Bark1 = <T = Animal>(x: T) => void;

interface IBark1 {
<T = Animal>(x: T): void;
}

递归声明

1
2
3
4
5
6
7
8
9
type Tree<P> = {
node: P,
leafs: Tree<P>[],
};

interface ITree<P> {
node: P;
leafs: Tree<P>[];
}

可索引的

1
2
3
4
5
6
7
type StringRecord = {
[index: string]: number,
};

interface IStringRecord {
[index: string]: number;
}

不同点
只能使用 type 来别名基本类型

1
2
3
4
5
6
7
type NewNumber = number;

interface INewNumber extends number {}
// 'number' only refers to a type, but is being used as a value here.

interface INewNumber extends Number {}
// 这样写是可以的,但是不要忘记 1 instanceof Number === false

元组
不能使用 interface 声明元组

1
2
3
4
5
6
7
8
9
10
11
type Tuples = [number, number];

interface ITuples {
0: number;
1: number;
}

[1, 2, 3] as Tuples;
// Conversion of type '[number, number, number]' to type 'Tuples' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of property 'length' are incompatible.

[1, 2, 3] as ITuples;

不相关的合集
只有 type 可以做不相关合集

1
type SomeAnimal = { type: Dog } | { type: Cat };

且不能对 不相关集合不能使用 extends 关键字

1
2
interface ISomeAnimal extends SomeAnimal {}
// An interface can only extend an object type or intersection of object types with statically known members

每个作用域只能声明一次类型

1
2
3
type Once = { a: string };
type Once = { b: string };
// Duplicate identifier 'Once'

可以在每个作用域中多次声明接口(会进行声明合并)

1
2
3
4
5
6
interface IOnce {
a: string;
}
interface IOnce {
b: string;
}
作者

大下坡

发布于

2020-02-11

更新于

2020-02-11

许可协议